package gen

import (
	"bytes"
	"fmt"
	"io/ioutil"

	"gopkg.in/goyy/goyy.v0/util/strings"
)

var controllerTemplate = `/** 
* go to java mybatis gen 
* @author hongyanyang1 
*/
package {{.Package}}.{{.ControllerPkg}}{{moduleCrePkg .}};

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import {{.Package}}.util.Results;
import {{.Package}}.{{.ServicePkg}}{{moduleCrePkg .}}.{{camel .Bean}}Service;
import {{.Package}}.{{.ControllerPkg}}.helper.BaseController;

@Controller
@RequestMapping(value = "/{{aamel .Bean}}")
public class {{camel .Bean}}Controller extends BaseController {
	@Autowired
	private {{camel .Bean}}Service {{aamel .Bean}}Service;
	
	@ResponseBody
	@RequestMapping(value = "/get")
	private String get{{camel .Bean}}(Integer id) {
		return Results.success({{aamel .Bean}}Service.get(id)).toJson();
	}
}
`

func GenController(genModules []Module) {
	fmt.Println("开始生成 Controller...")
	for _, genModule := range genModules {
		if genModule.IsGenController {
			var project = genModule.SProject
			var cloums = genModule.Cloums
			var dir = PackageDir(genModule, "controller")
			MkdirAll(dir)
			for tableName, cloums := range cloums {
				buf := bytes.Buffer{}
				var tempData = NewTempData(tableName, cloums, project, genModule)
				templ := NewTmpl(controllerTemplate)
				templ.Execute(&buf, tempData)
				fmt.Println(buf.String())
				err := ioutil.WriteFile(dir+"\\"+strings.Camel(tempData.Bean)+"Controller.java", buf.Bytes(), 0755)
				if err != nil {
					fmt.Println(err.Error())
				}
			}
		}
	}
}
